//
//  MallOrderContentViewController.m
//  CYWFrame
//
//  Created by Macx on 2017/9/15.
//  Copyright © 2017年 Macx. All rights reserved.
//

#import "MallOrderContentViewController.h"
#import "MallCommitOrdersViewController.h"
#import "MallOrderGoodTableViewCell.h"
#import "ShopHeaderCell.h"
#import "ShopOrderFooterCell.h"
#import "MallDetailViewController.h"
#import "OrderGoods.h"
#import "PostsTextViewController.h"
#import "MallLogisticsViewController.h"
#import "NSString+Common.h"
#import <Masonry.h>
#import "ZYInputAlertView.h"

@interface MallOrderContentViewController () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, assign) NSInteger page; //网络请求页数
@property (nonatomic, strong) NSMutableArray *orderGoodArr;
@property (nonatomic, strong) NSString *orderStatus;
@property (nonatomic, strong) NSArray *orderFootArr;

@end

@implementation MallOrderContentViewController {
    UITableView     *_tableView;
    MallOrderGoodTableViewCell  *_cell;
    
    UIView          *_shopOwnerBgView;
    UIImageView     *_shopOwnerImg;
    UILabel         *_shopOwnerName;
    
    UILabel         *_goodNum;
    UILabel         *_goodMoney;
    
    CGSize          _size1;
}

- (void)viewWillAppear:(BOOL)animated
{
	[self GETOederList];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tableViewReload:) name:@"reloadMall" object:nil];
    
    self.page = 1;
    
    [self createUI];
    
    [self GETOederList];
    
    [self refreshData];
    
    
}

// 主页tableView是否滚动接收到通知
//- (void)tableViewReload:(NSNotification *)notification {
//    NSLog(@"滑动分栏，进行刷新");
//    [_tableView reloadData];
//}

//移除广播监听。
//-(void)dealloc{
//    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"reloadMall" object:nil];
//}



#pragma mark ==========构建UI==========
- (void)createUI {
    
    self.view.backgroundColor = UISeparatedColorRGB;
    
    if ([self.statusStr isEqualToString:@"unpaid"]) {
        self.orderStatus = @"待付款";
        self.orderFootArr = @[@"取消订单", @"付款"];
    }
    else if ([self.statusStr isEqualToString:@"paid"]) {
        self.orderStatus = @"已支付";
		//后台没有提醒收发货的功能，隐藏先。。
        //self.orderFootArr = @[@"提醒收货"];
		self.orderFootArr = @[];
    }
    else if ([self.statusStr isEqualToString:@"delivered"]) {
        self.orderStatus = @"已发货";
        self.orderFootArr = @[@"查看物流", @"确认收货"];
    }
    else {
        self.orderStatus = @"交易完成";
        self.orderFootArr = @[@"删除订单"];
    }
    
    
    _size1 = [LZCTools textSizeWithText:@"字数" font:kUHSystemFontWithSize(12)];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 1, SCREEN_WIDTH, SCREEN_HEIGHT-60-49) style:UITableViewStyleGrouped];
    [self.view addSubview:_tableView];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.tableFooterView = [[UIView alloc]init];
    
    [_tableView registerNib:[UINib nibWithNibName:@"MallOrderGoodTableViewCell" bundle:nil] forCellReuseIdentifier:@"order"];
    
    [_tableView registerNib:[UINib nibWithNibName:@"ShopHeaderCell" bundle:nil] forCellReuseIdentifier:@"header"];
    
    [_tableView registerNib:[UINib nibWithNibName:@"ShopOrderFooterCell" bundle:nil] forCellReuseIdentifier:@"footer"];
    
    
}

#pragma mark ==========更新数据==========
- (void)refreshData {
    __weak typeof (self) weakSelf = self;
    
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        NSLog(@"下拉刷新");
        weakSelf.page = 1;
        [weakSelf GETOederList];
    }];
    
    _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        NSLog(@"上拉加载");
        weakSelf.page++;
        [weakSelf GETOederList];
    }];
    
}


#pragma mark ==========UITableView==========
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	
	MallOrderGoodTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"order" forIndexPath:indexPath];
    //_cell = [tableView dequeueReusableCellWithIdentifier:@"order" forIndexPath:indexPath];
    
    NSDictionary *dict = self.orderGoodArr[indexPath.section];
    //OrderGoods *model = ((NSArray *)dict[@"items"])[indexPath.row];
    OrderGoods *model = [[OrderGoods alloc] init];
    [model setValuesForKeysWithDictionary:((NSArray *)dict[@"items"])[indexPath.row]];
    model.order_id = dict[@"order_id"];
    model.is_commented = dict[@"is_commented"];
    cell.model = model;
    
//    NSLog(@"%@", _cell.contentView.subviews);
    
    if ([self.statusStr isEqualToString:@"received"]) {
		[cell.contentView.subviews.lastObject removeFromSuperview];
        UIButton *btn;
		btn = [UIButton buttonWithType:UIButtonTypeCustom];
		[cell.contentView addSubview:btn];
		CGFloat btnW = _size1.width*2 + 10;
		CGFloat x = SCREEN_WIDTH - (10+btnW);
		btn.frame = CGRectMake(x, cell.contentView.height-10-(_size1.height+5), btnW, _size1.height+5);
		btn.titleLabel.font = kUHSystemFontWithSize(12);
		btn.layer.borderWidth = 1;
		btn.layer.cornerRadius = 10;
		btn.layer.masksToBounds = YES;
		
		NSLog(@"commented is %@", model.is_commented);
		if ([model.is_commented isEqualToString:@"1"]) {
			[btn setTitle:@"已评价" forState:UIControlStateNormal];
			btn.layer.borderColor = kGrayColor.CGColor;
			[btn setTitleColor:kGrayColor forState:UIControlStateNormal];
			btn.enabled = NO;
		}
		else
		{
			NSLog(@"commented is %@", model.is_commented);
			[btn setTitle:@"评价" forState:UIControlStateNormal];
			btn.layer.borderColor = kRedColor.CGColor;
			[btn setTitleColor:kRedColor forState:UIControlStateNormal];
			[btn addActionWithblock:^{
				PostsTextViewController *postVC = [[PostsTextViewController alloc] init];
				postVC.type = @"1";
				postVC.goodId = [NSString stringWithFormat:@"%@", [model valueForKey:@"goods_id"]];
				postVC.order_id = model.order_id;
				[self presentViewController:postVC animated:YES completion:nil];
			}];
		}
    }
    return cell;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.orderGoodArr.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSDictionary *dict = self.orderGoodArr[section];
    return ((NSArray *)dict[@"items"]).count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 2*SW(9)+10;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSLog(@"点击tableView.cell = %ld", indexPath.row);
    
    NSDictionary *dict = self.orderGoodArr[indexPath.section];
    OrderGoods *model = ((NSArray *)dict[@"items"])[indexPath.row];
    
    MallDetailViewController *detailVC = [[MallDetailViewController alloc] init];
    detailVC.goodId = [[model valueForKey:@"goods_id"] integerValue];
    [self.navigationController pushViewController:detailVC animated:YES];
}
//   tableView代理方法 设置分区高度（可以根据不同分区设置不同高度等实现自定义）
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return _size1.height+40;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
	NSDictionary *orderDict = self.orderGoodArr[section];
	NSString *refundStatus = orderDict[@"refund_status"];
	NSString *settlement = orderDict[@"settlement"];
	if ([self.statusStr isEqualToString:@"received"] && [refundStatus isEqualToString:@"3"] && [settlement isEqualToString:@"0"]) {
		return 118;
	}
	else {
		return 89;
	}
	
}

//  自定义分区头的view
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    ShopHeaderCell *hf = [tableView dequeueReusableCellWithIdentifier:@"header"];
    NSString *imgStr = [[self.orderGoodArr[section] valueForKey:@"shop"] valueForKey:@"photo"];
    [hf.pic sd_setImageWithURL:[NSURL URLWithString:imgStr] placeholderImage:IMAGE(@"placeHolder")];
	
	NSDictionary *orderDict = self.orderGoodArr[section];
    hf.state.text = self.orderStatus;
	if ([orderDict[@"is_ecbuy"] isEqualToString:@"1"]) {
		hf.state.text = [self.orderStatus stringByAppendingString:@"(拼单)"];
		[hf.state sizeToFit];
	}
    hf.name.text = [[self.orderGoodArr[section] valueForKey:@"shop"] valueForKey:@"shop_name"];
    
    return hf;
    
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    
    ShopOrderFooterCell *ff = [tableView dequeueReusableCellWithIdentifier:@"footer"];
    
    
    int num = 0;
    float price = 0.0;
    float express_fee = 0.0;

    NSDictionary *orderDict = self.orderGoodArr[section];

    num = (int)((NSArray *)orderDict[@"items"]).count;
    price = [orderDict[@"total_price"] floatValue]/100;
    express_fee = [orderDict[@"express_fee"] floatValue]/100;

    if (express_fee == 0.0) {
        ff.price.text = [NSString stringWithFormat:@"合计:%.2lf(免运费)", price];
    }
    else
        ff.price.text = [NSString stringWithFormat:@"合计:%.2lf(运费:%.2lf)", price, express_fee];

    ff.num.text = [NSString stringWithFormat:@"共%d件商品", num];
    
    UILabel *time = [[UILabel alloc] initWithFrame:CGRectMake(10, 54, SW(2), 20)];
    [ff.contentView addSubview:time];
    time.textColor = kGrayColor;
    time.font = kUHSystemFontWithSize(12);
    time.text = [NSString timeWithTimeIntervalString:orderDict[@"create_time"]];
	
	NSString *orderId = orderDict[@"order_id"];
	NSString *expressNum = orderDict[@"express_no"];
	NSString *settlement = orderDict[@"settlement"];	//是否需要显示退货按钮
	NSString *refundStatus = orderDict[@"refund_status"];
	NSString *refundRemark = orderDict[@"refund_remark"];
	NSString *phone = orderDict[@"shop"][@"tel"];
	if ([self.statusStr isEqualToString:@"received"]) {
		ff.contactWithOwner.hidden = NO;
		[ff.contactWithOwner addActionWithblock:^{
			NSMutableString *tstr=[[NSMutableString alloc] initWithFormat:@"tel:%@", phone];
			NSLog(@"手机号======%@",tstr);
			[[UIApplication sharedApplication] openURL:[NSURL URLWithString:tstr] options:@{} completionHandler:nil];
		}];
	}
	
	NSLog(@"the settlement is %@", settlement);
	NSLog(@"the refundStatus is %@", refundStatus);
    for (int i = 0; i < self.orderFootArr.count; i++) {
		//如果单号是空的，则第一个按钮变成显示“配送中”标签
		if ([NSString isEmpty:expressNum] && (i == 0) && [self.statusStr isEqualToString:@"delivered"]) {
			CGFloat btnW = _size1.width*2 + 10;
			CGFloat x = SCREEN_WIDTH - (10+btnW)*(self.orderFootArr.count-i);
			UILabel *expressL = [[UILabel alloc] initWithFrame:CGRectMake(x, 0, btnW, _size1.height+5)];
			expressL.centerY = ff.contentView.height-25;
			expressL.text = @"配送中";
			expressL.textColor = UIMainColorRGB;
			expressL.font = [UIFont systemFontOfSize:14];
			expressL.textAlignment = NSTextAlignmentCenter;
			[ff.contentView addSubview:expressL];
			continue;
		}
		
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [ff.contentView addSubview:btn];
        CGFloat btnW = _size1.width*2 + 10;
        CGFloat x = SCREEN_WIDTH - (10+btnW)*(self.orderFootArr.count-i);
        btn.frame = CGRectMake(x, 0, btnW, _size1.height+5);
        btn.centerY = time.centerY;
        btn.titleLabel.font = kUHSystemFontWithSize(12);
        [btn setTitle:self.orderFootArr[i] forState:UIControlStateNormal];
        btn.layer.borderWidth = 1;
        btn.layer.cornerRadius = 10;
        btn.layer.masksToBounds = YES;
		
		//根据后台字断判断是否应该显示退货按钮
		if ((i == 0) && [self.statusStr isEqualToString:@"received"] &&
			[settlement isEqualToString:@"0"]) {
			UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
			[ff.contentView addSubview:btn];
			CGFloat btnW = _size1.width*2 + 10;
			CGFloat x = SCREEN_WIDTH - (10+btnW)*2;
			btn.frame = CGRectMake(x, 0, btnW, _size1.height+5);
			btn.centerY = time.centerY;
			btn.titleLabel.font = kUHSystemFontWithSize(12);
			if ([refundStatus isEqualToString:@"0"]) {
				NSLog(@"i was heerererererer");
				[btn setTitle:@"退货" forState:UIControlStateNormal];
				btn.layer.borderWidth = 1;
				btn.layer.cornerRadius = 10;
			}
			else if([refundStatus isEqualToString:@"1"]){
				[btn setTitle:@"退款成功" forState:UIControlStateNormal];
				btn.userInteractionEnabled = NO;
			}
			
			//下面这有点长，x再往左挪10
			else if([refundStatus isEqualToString:@"2"]){
				[btn setTitle:@"退款审核中" forState:UIControlStateNormal];
				btn.frame = CGRectMake(x-10, 0, btnW+15, _size1.height+5);
				btn.userInteractionEnabled = NO;
			}
			else {
				[btn setTitle:@"再次申请" forState:UIControlStateNormal];
				btn.frame = CGRectMake(x, 0, btnW+15, _size1.height+5);
				UILabel *refuseRemark = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH-30, 25)];
				refuseRemark.font = [UIFont systemFontOfSize:12];
				[refuseRemark setTextColor:kGrayColor];
				refuseRemark.text = [NSString stringWithFormat:@"驳回理由:%@",refundRemark];
				refuseRemark.numberOfLines = 0;
				[refuseRemark sizeToFit];
				[ff.contentView addSubview:refuseRemark];
				[refuseRemark mas_makeConstraints:^(MASConstraintMaker *make) {
					make.left.mas_equalTo(time);
					make.right.mas_equalTo(ff).offset(-5);
					make.top.mas_equalTo(time.mas_bottom).offset(8);
				}];
			}
			btn.centerY = time.centerY;
			btn.layer.masksToBounds = YES;
			btn.layer.borderColor = kGrayColor.CGColor;
			[btn setTitleColor:kGrayColor forState:UIControlStateNormal];
			[btn addActionWithblock:^{
				ZYInputAlertView *alertView = [ZYInputAlertView alertView];
				alertView.placeholder = @"请输入退货原因";
				alertView.maxLength = 50;
				[alertView confirmBtnClickBlock:^(NSString *inputString) {
					NSDictionary *param = @{
											@"refund_remark":inputString,
											@"order_id":orderId
											};
					[[NetworkTool sharedTool] requestWithName:@"申请退货" URLString:APIRefundOrder parameters:param method:@"POST" callBack:^(id responseObject) {
						[LZCTools HUDMessage:@"申请提交成功" delay:1.0];
						[self GETOederList];
					}];
				}];
				[alertView show];
			}];
			
		}

        if (i==0) {
            btn.layer.borderColor = kGrayColor.CGColor;
            [btn setTitleColor:kGrayColor forState:UIControlStateNormal];
        }
        else {
            btn.layer.borderColor = kRedColor.CGColor;
            [btn setTitleColor:kRedColor forState:UIControlStateNormal];
        }
        
        btn.tag = (section+1)*1000+i; // 确定数据
        
        [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        
    }
    
    return ff;

}


#pragma mark ==========响应方法==========
- (void)GETOederList {
    
    NSDictionary *param = @{@"status":self.statusStr,
                            @"page":[NSString stringWithFormat:@"%ld", self.page],
                            @"per_page":@"10"};
    
    NSString *name = [NSString stringWithFormat:@"获取 %@ 订单", self.statusStr];
    
    [[NetworkTool sharedTool] requestWithName:name URLString:APIMallsOrders parameters:param method:@"GET" callBack:^(id responseObject) {
        
        
        if (self.page == 1) {
            [self.orderGoodArr removeAllObjects];
        }
        
        NSArray *arr = responseObject[@"data"];
        if (arr.count == 0) {
            self.page--;
            if (self.page == 0) {
                self.page = 1;
            }
        }
        
        self.orderGoodArr = [self.orderGoodArr arrayByAddingObjectsFromArray:arr].mutableCopy;
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [_tableView.mj_header endRefreshing];
            [_tableView.mj_footer endRefreshing];
            [_tableView reloadData];
        });
    }];
    
}

- (void)btnClick:(UIButton *)btn {
    NSLog(@"点击  %@  ==  %ld", self.statusStr, btn.tag);
    
    NSInteger section = btn.tag/1000 - 1;
    NSLog(@"%ld", section);
    
    NSDictionary *orderDict = self.orderGoodArr[section];
    NSString *orderId = orderDict[@"order_id"];
    
    if ([self.statusStr isEqualToString:@"unpaid"]) {
        if (btn.tag%2 == 0) {
            NSString *url = [NSString stringWithFormat:@"%@/%@", APIMallsOrders, orderId];
            
            [[NetworkTool sharedTool] requestWithName:@"取消订单" URLString:url parameters:nil method:@"DELETE" callBack:^(id responseObject) {
                
                [self.orderGoodArr removeObjectAtIndex:section];
                [_tableView reloadData];
            }];
        }
        else {
            MallCommitOrdersViewController *commitVC = [[MallCommitOrdersViewController alloc] init];
            commitVC.orderData = @[self.orderGoodArr[section]]; // 介于购物车缘故，传递数组
            [self.navigationController pushViewController:commitVC animated:YES];
        }
        
    }
    else if ([self.statusStr isEqualToString:@"paid"]) {
        [LZCTools HUDMessage:@"提醒成功" delay:2.0];
    }
    else if ([self.statusStr isEqualToString:@"delivered"]) {
        if (btn.tag%2 == 0) {
            MallLogisticsViewController *logisticsVC = [[MallLogisticsViewController alloc] init];
            logisticsVC.goodId = orderId;
            [self.navigationController pushViewController:logisticsVC animated:YES];
        }
        else {
            NSString *url = [NSString stringWithFormat:@"%@/%@/receive-status", APIMallsOrders, orderId];
            
            [[NetworkTool sharedTool] requestWithName:@"确认收货" URLString:url parameters:nil method:@"PUT" callBack:^(id responseObject) {
                [self.orderGoodArr removeObjectAtIndex:section];
                [_tableView reloadData];
            }];
        }
    }
    else {
        NSString *url = [NSString stringWithFormat:@"%@/%@/hidden", APIMallsOrders, orderId];
        [[NetworkTool sharedTool] requestWithName:@"删除订单" URLString:url parameters:nil method:@"PUT" callBack:^(id responseObject) {
            [self.orderGoodArr removeObjectAtIndex:section];
            [_tableView reloadData];
        }];
        
    }
    
}


// 懒加载
- (NSMutableArray *)orderGoodArr {
    if (_orderGoodArr == nil) {
        _orderGoodArr = [[NSMutableArray alloc] init];
    }
    return _orderGoodArr;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
